<template>
	<view>
		<uni-popup ref="popup" style="flex:0;!important">
			<!-- <view v-show="IfLinked == false  && toggleIndex == 1 && !list.length"> -->
			<view v-show="this.list.length == 0 && IfLinked == false">
				<view class="ensure" style="text-align: center;font-weight: bold;border-radius: 20rpx 20rpx 0 0;">
					<view class="title" style="text-align: center;position: relative;padding-top: 20rpx;">选择打印机<text
							@click="close" class="iconfont icon-guanbi5"
							style="position: absolute;right: 30rpx; top: 0;padding-top: 20rpx;"></text></view>

					<view style="margin: 60rpx 0 20rpx 0;">
						<uni-icons type="info-filled" color="red" size="58"></uni-icons>
					</view>
					<text>未检测到可用打印机，请检查蓝牙是否开启，或打印机是否正常</text>
					<button class="bg_color" style="margin: 20rpx;border-radius: 18rpx;color: #fff;padding: 20rpx;"
						@click="close">我知道了</button>
				</view>
			</view>

			<view v-show="list.length > 0 || deviceId != null">
				<view class="ensure" style="text-align: center;font-weight: bold;border-radius: 20rpx 10rpx 0 0;">
					<view class="text title" style="padding: 20rpx;">
						<!-- <text class="text-left" @click="goPrintSetting(1)">
							打印设置
						</text> -->
						<text class="text-left" @click="openPrintSetting('left')">
							打印设置
						</text>
						<text class="center">选择打印机</text>
						<text @click="close" class="iconfont icon-guanbi5"></text>
					</view>
					<view class="u-page__checkbox-item" style="margin: 0 20rpx;">
						<!-- <u-radio-group v-model="radiovalue1" :borderBottom="true" placement="column"
							iconPlacement="right">
							<u-radio shape="circle" :customStyle="{marginBottom: '16px'}" v-for="(ele, index) in list"
								:key="index" :name="ele.name" @change="connectPrinter(ele)">
								{{ele.name}}{{deviceId == ele.deviceId?'（已连接）':''}}
							</u-radio>
						</u-radio-group> -->
						<radio-group v-model="radiovalue1" @change="connectPrinter(ele)">
							<label style="display: flex;flex-direction: row;margin: 20rpx;border-bottom: 1px solid #eee;padding: 20rpx 0;"
								v-for="(ele, index) in list" :key="index">
								<view>
									<radio :value="JSON.stringify(ele)" :checked="ele.name === radiovalue1"/>
								</view>
								<view style="line-height: 19px;">{{ele.name}}{{deviceId == ele.deviceId?'（已连接）':''}}</view>
							</label>
						</radio-group>
					</view>
					<view class="popup_button" style="display: flex;">
						<button
							style="margin: 30rpx 20rpx 0 20rpx;border-radius: 18rpx;color: #fff;background-color: #808080;padding: 20rpx;flex: 1;"
							@click="sendBleLabelTest()">打印测试页</button>
						<button class="bg_color"
							style="margin: 30rpx 20rpx 0 20rpx;border-radius: 18rpx;color: #fff;padding: 20rpx;flex: 1;"
							@click="close">断开连接</button>
					</view>
				</view>
			</view>
		</uni-popup>

		<!-- 组件 -->
		<uni-popup ref="setPopup" overlay="true" style="flex:0;!important;">
			<PrintSetting ref="settingRefs" :printerConfig.sync="printerConfig" @sendBleLabelSelfTest="sendBleLabelSelfTest"
				@setPrinterConfig="setPrinterConfig" :printer="printer"></PrintSetting>
		</uni-popup>
		<printerCore ref="printer" :showLog="false" @deviceListChange="deviceListChange"></printerCore>
	</view>

</template>

<script>
	import UniSection from '@/components/uni/uni-swipe-action/uni-swipe-action.vue';
	import printerCore from '../../printer_sdk/printer_core.vue';
	import PrintSetting from '../print-setting.vue';
	//历史连接信息key
	const HIS_CONNECT_DEVICE_KEY = "HIS_CONNECT_DEVICE_KEY";

	export default {
		components: {
			'uni-section': UniSection,
			printerCore,
			PrintSetting
		},
		props: {
			IfLinked: {
				type: Boolean,
				default: true
			},
			toggleIndex: {
				type: Number,
				default: ''
			},
		},
		data() {
			return {
				radiovalue1: '', // 复选框的值
				// -------
				deviceId: null, //当前连接的蓝牙地址
				list: [],
				isScanning: false,
				isLabelSend: false,
				msg: "",
				printer: null, //打印机实例 //this.$refs.printer;

				tableValues: [ //打印的标签数据
					{
						id: 3, // 任务id
						name: "打印容器码模板 2个",
						tables: [{
								templateId: 21, //打印容器码模板
								count: 1, //打印数量
								values: [
									"ZK2024011212346",
								],
							},
							{
								templateId: 21, //打印容器码模板
								count: 1, //打印数量
								values: [
									"ZK2024011212347",
								],
							},
						],
						// tables: [{ //要打印的标签数据
						// 	templateId: 1, //标准商品模板
						// 	count: 1, //打印数量
						// 	values: [
						// 		"[雅士康]一次性竹筷5.5x200mm1000双", //品牌+商品名称
						// 		"10斤/袋(1000双)", //SKU名称
						// 		"1312", //商品id
						// 		"7434", //SKU商品id
						// 		"北京大兴仓",
						// 		"慧源商贸",
						// 		"20240112203002", //条形码 待定
						// 		"2024011220300200012", //二维码 唯一商品标签号码 年月日时分秒毫秒+2随机
						// 		"打印日期:2024-01-12",
						// 		"客服电话:400-0616-007",
						// 	],
						// }]
						// tables: [{
						// 	templateId: 11, //标准商品换品模板
						// 	count: 1, //打印数量
						// 	values: [
						// 		"[雅士康]一次性竹筷5.5x200mm1000双",
						// 		"10斤/袋(1000双)",
						// 		"本次大约 1 袋",
						// 	],
						// }]

					},
				],
				printerConfig: { //打印机配置
					sizeX: 40, //标签长(mm) 70
					sizeY: 30, //标签宽(mm) 50
					gap: 2, //标签间隔(mm)
					speed: 5, //打印速度(1 - 6)
					density: 8, //打印浓度(1 - 15)
					direction: 1, //打印方向 1.出纸方向 0.进纸方向
				}
			}
		},
		watch: {
			msg() {
				if (this.msg) {
					uni.showToast({
						title: this.msg,
						icon: "none"
					});
					this.msg = null;
				}
			}
		},
		//页面组件加载完成
		onReady() {
			this.printer = this.$refs.printer;
			//开始自动打开蓝牙搜索设备（自动连接上一次连接的打印机）
			this.autoConnectPrinter();
			let device = uni.getStorageSync(HIS_CONNECT_DEVICE_KEY);
			if (device) {
				this.printerConfig = device;
			}
		},
		methods: {
			toggle(type, ele) {
				this.type = type;
				// open 方法传入参数 等同在 uni-popup 组件上绑定 type属性
				this.$refs.popup.open(type);
			},

			// 提醒连接打印机的---关闭--弹窗
			close() {
				this.$refs.popup.close();
			},

			openPrintSetting(type, ele) {
				this.type = type;
				this.$refs.setPopup.open(type);
			},

			//去设置打印
			goPrintSetting(ele) {
				this.goPage('/pages/labelPrinting/printSettings/printSettings?item=add')
			},

			goPage(url) {
				uni.navigateTo({
					url
				})
			},
			//搜索打印机设备
			startSearch() {
				let that = this;
				this.isScanning = true;

				this.$refs.printer.startSearch((res) => {
					this.isScanning = false;
					if (res.code != 0) {
						that.msg = res.msg;
					}
				});
			},
			//连接蓝牙设备
			connectPrinter(device) {
				let radioValue = JSON.parse(device);
				// this.msg = "请求连接设备:" + device.name;
				this.msg = "请求连接设备:" + radioValue.name;
				let that = this;
				this.isScanning = true;

				this.$refs.printer.connectPrinter(radioValue, (res) => {
					that.isScanning = false;
					if (res.code != 0) {
						that.msg = res.msg;
					} else {
						that.msg = "连接成功！";
						that.deviceId = radioValue.deviceId;
						for (let i = 0; i < this.list.length; i++) {
							if (that.deviceId == this.list[i].deviceId) {
								this.$emit('update:IfLinked', true) //返回给上级，改变连接状态
							}
						}
					}
				});
			},
			/**
			 * 自动连接打印机
			 */
			autoConnectPrinter() {
				let that = this;
				this.isScanning = true;
				this.printer.autoConnectPrinter((res, device) => {
					that.isScanning = false;

					if (res.code != 0) {
						that.msg = res.msg;
					} else {
						that.msg = "自动连接成功！";
						that.deviceId = device.deviceId;
						that.radiovalue1 = device.name;
						this.$emit('update:IfLinked', true) //返回给上级，改变连接状态
					}
				});
			},
			//蓝牙设备列表更新事件
			deviceListChange(deviceList) {
				this.list = deviceList;
			},

			//打印标签
			sendBleLabel(tableValue) {
				tableValue.config = this.printerConfig; //必传，用于根据大小自适应模板
				let that = this;
				this.isLabelSend = true;
				this.$refs.printer.sendBleLabel(
					tableValue,
					(res, item, printNumState) => {
						if (res.code == 0) {
							that.msg = `打印中... ${printNumState.progress}%`;
							if (printNumState.progress == 100) {
								that.msg = "打印完成！";
								that.isLabelSend = false;
							}
						} else {
							that.msg = res.msg;
							that.isLabelSend = false;
						}
					});

			},
			//打印标签自检页（设置页面使用）
			sendBleLabelSelfTest() {
				let that = this;
				this.isLabelSend = true;
				this.$refs.printer.sendBleLabelSelfTest(
					(res, item, printNumState) => {
						if (res.code == 0) {
							that.msg = `打印中... ${printNumState.progress}%`;
							if (printNumState.progress == 100) {
								that.msg = "打印完成！";
								that.isLabelSend = false;
							}
						} else {
							that.msg = res.msg;
							that.isLabelSend = false;
						}
					});
			},

			//打印标签测试页（连接页面使用）
			sendBleLabelTest() {
				let tableItem = {
					config: this.printerConfig, //必传，用于根据大小自适应模板 默认 70*50 
					templateId: 1, //要测试的模板 ID 可为null 默认1 标准商品模板
				}
				let that = this;
				this.isLabelSend = true;
				this.$refs.printer.sendBleLabelTest(
					(res, item, printNumState) => {
						if (res.code == 0) {
							that.msg = `打印中... ${printNumState.progress}%`;
							if (printNumState.progress == 100) {
								that.msg = "打印完成！";
								that.isLabelSend = false;
							}
						} else {
							that.msg = res.msg;
							that.isLabelSend = false;
						}
					},
					templateId
				);
			},

			//打印机配置
			setPrinterConfig(printerConfig) {
				this.printerConfig = printerConfig;
				let that = this;
				this.isLabelSend = true;
				this.$refs.printer.setPrinterConfig(
					this.printerConfig,
					(res, item, printNumState) => {
						if (res.code == 0) {
							that.msg = `配置中... ${printNumState.progress}%`;
							if (printNumState.progress == 100) {
								that.msg = "配置完成！";
								that.isLabelSend = false;
								uni.setStorageSync(HIS_CONNECT_DEVICE_KEY, item.config);
							}
						} else {
							that.msg = res.msg;
							that.isLabelSend = false;
						}
					}
				)
			},

			//打印指定数量容器码
			sendBleLabelContainerCode(counts) {
				let count = counts;
				let tables = [];

				for (var i = 0; i < count; i++) {
					let key = "ZK" + this.getDateTimeStr() + (i + 1);
					tables.push({
						templateId: 21, //打印容器码模板
						count: 1, //打印数量
						values: [
							key
						],
					})
				}

				let tableValue = {
					tables: tables,
					config: this.printerConfig
				};
				this.sendBleLabel(tableValue);
			},

			getDateTimeStr() {
				var currentDate = new Date();
				var year = currentDate.getFullYear();
				var month = ('0' + (currentDate.getMonth() + 1)).slice(-2);
				var day = ('0' + currentDate.getDate()).slice(-2);
				var hours = ('0' + currentDate.getHours()).slice(-2);
				var minutes = ('0' + currentDate.getMinutes()).slice(-2);
				var seconds = ('0' + currentDate.getSeconds()).slice(-2);

				var formattedDate = year + month + day + hours + minutes + seconds;
				return formattedDate;
			},
		}
	}
</script>

<style lang="scss">
	// 动态颜色
	.bg_color {
		@include main_bg_color(theme);
	}

	.ensure {
		// width: 100%;
		background-color: #fff;
		padding-bottom: 22rpx;
		padding-bottom: calc(22rpx+ constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
		padding-bottom: calc(22rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/

		// .title {
		// 	font-size: 32rpx;
		// 	color: #282828;
		// 	text-align: center;
		// 	margin: 38rpx 0 36rpx 0;
		// 	position: relative;

		// 	.iconfont {
		// 		color: #808080;
		// 		position: absolute;
		// 		right: 30rpx;
		// 		top: 0;
		// 		font-size: 36rpx;
		// 	}
		// }
		.text.title {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 50rpx;
		}

		.text-left {
			// flex: 1;
			text-align: left;
		}

		.center {
			flex: 1;
			text-align: center;
		}

		.right {
			color: #808080;
			flex: 1;
			text-align: right;
			font-size: 36rpx;
		}
	}
</style>